package kxfang.com.login.ui;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ToastUtils;
import com.orhanobut.hawk.Hawk;


import kxfang.com.base.activity.MvvmBaseActivity;
import kxfang.com.base.utils.GsonUtils;
import kxfang.com.base.viewmodel.MvmBaseViewModel;
import kxfang.com.common.config.HttpConfig;
import kxfang.com.common.constant.Constant;
import kxfang.com.common.dialog.WaitDialog;
import kxfang.com.common.router.RoutHub;
import kxfang.com.common.utils.RouterUtils;
import kxfang.com.common.utils.StatusBarUtil;
import kxfang.com.common.utils.Validator;
import kxfang.com.http.EasyHttp;
import kxfang.com.http.callback.SimpleCallBack;
import kxfang.com.http.exception.ApiException;
import kxfang.com.login.R;
import kxfang.com.login.bean.AppUser;
import kxfang.com.login.bean.MsgModel;
import kxfang.com.login.databinding.LoginActivityBindPhoneBinding;
import kxfang.com.login.parameter.GetCodePar;
import kxfang.com.common.parameter.LoginPar;

import static kxfang.com.common.constant.Constant.yqID;

public class BindPhoneActivity extends MvvmBaseActivity<LoginActivityBindPhoneBinding, MvmBaseViewModel> {

    GetCodePar getCodePar = new GetCodePar();
    LoginPar par = new LoginPar();
    private WaitDialog.Builder waitDialog;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtil.setTopActivityView(this, viewDataBinding.topView);
        initView();
    }
    @Override
    protected MvmBaseViewModel getViewModel() {
        return null;
    }

    @Override
    protected int getBindingVariable() {
        return 0;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.login_activity_bind_phone;
    }

    @Override
    protected void onRetryBtnClick() {

    }

    private void initView() {
        try {
            ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
            ClipData data = cm.getPrimaryClip();
            ClipData.Item item = data.getItemAt(0);
            if (data.getItemAt(0) != null) {
                yqID = item.getText().toString();
                if (yqID != null) {
                    // 清除剪贴板
                    ClipData clip = ClipData.newPlainText("", "");
                    cm.setPrimaryClip(clip);
                }
            }
        } catch (Exception e) {

        }

        viewDataBinding.activityBack.setOnClickListener(view -> finish());
        Intent intent = getIntent();
        //三方登录类型
        int type = intent.getIntExtra("ThirdType", 0);
        //三方登录openId
        String id = intent.getStringExtra("ThirdID");
        viewDataBinding.getCodeText.setOnClickListener(v -> {
            if (!Validator.isMobile(viewDataBinding.phoneText.getText().toString())) {
                ToastUtils.showShort("请输入正确的手机号码");
                return;
            }
            getCode();
        });
        viewDataBinding.bindButton.setOnClickListener(v -> {
            par.setThirdType(type);
            par.setThirdID(id);
            par.setPromotersID(yqID);
            String yzm = viewDataBinding.codeEdit.getText().toString();
            String phone = viewDataBinding.phoneText.getText().toString();
            if (TextUtils.isEmpty(yzm)){
                ToastUtils.showShort("验证码不能为空!");
                return;
            }
            if (TextUtils.isEmpty(phone)){
                ToastUtils.showShort("手机号不能为空!");
                return;
            }
            par.setYzm(yzm);
            par.setPhone(phone);
            par.setPersonType(7);
            login(par);
        });
    }

    //获取验证码
    private void getCode() {
        timer.start();
        getCodePar.setPhone(viewDataBinding.phoneText.getText().toString());
        getCodePar.setVeriCode(7);
        loadCode(getCodePar);
    }

    CountDownTimer timer = new CountDownTimer(60000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            viewDataBinding.getCodeText.setEnabled(false);
            viewDataBinding.getCodeText.setText("已发送(" + millisUntilFinished / 1000 + ")");
        }

        @Override
        public void onFinish() {
            viewDataBinding.getCodeText.setEnabled(true);
            viewDataBinding.getCodeText.setText("获取验证码");
        }
    };

    //请求验证码
    private void loadCode(GetCodePar par) {
        EasyHttp.post(HttpConfig.loadCode)
                .cacheKey(HttpConfig.loadCode.concat(BindPhoneActivity.class.getSimpleName()))
                .upJson(GsonUtils.toJson(par))
                .execute(new SimpleCallBack<MsgModel>() {
                    @Override
                    public void onSuccess(MsgModel msgModel) {
                        if (msgModel.getCode() != 200) {
                            ToastUtils.showShort(msgModel.getMsg());
                        }
                    }

                    @Override
                    public void onError(ApiException e) {

                    }

                    @Override
                    public void onCompleted() {
                        timer.onFinish();
                    }
                });
    }


    //登录
    private void login(LoginPar par) {
        waitDialog = new WaitDialog.Builder(this);
        waitDialog.setMessage("登录中...").show();
        EasyHttp.post(HttpConfig.login)
                .cacheKey(HttpConfig.login.concat(BindPhoneActivity.class.getSimpleName()))
                .upJson(GsonUtils.toJson(par))
                .execute(new SimpleCallBack<AppUser>() {
                    @Override
                    public void onSuccess(AppUser appUser) {
                        Hawk.put("head", appUser.getHead());
                        Hawk.put("ctype", appUser.getCtype());
                        Hawk.put("phone", appUser.getPhone());
                        Hawk.put(Constant.HAWK_USER_INFO, appUser.getId());
                        Hawk.put("alias", appUser.getAlias());
                        if (appUser.getThirdInfo() != null)
                            Hawk.put("thirdInfo", appUser.getThirdInfo());
                        Hawk.put("statu", appUser.getStatu());
                        Hawk.put("isnew", appUser.getIsNew());

                        RouterUtils.navigate(RoutHub.PAGER_MAIN);
                        finish();
                    }

                    @Override
                    public void onError(ApiException e) {

                    }

                    @Override
                    public void onCompleted() {
                        waitDialog.dismiss();
                    }
                });



    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }


}
